﻿package loader
{
	
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	/**
	 * @author yes3d
	 * @version 1.0
	 * @created 23-����-2009 14:39:25
	 */
	public class XmlLoader extends EventDispatcher
	{
		private var _xml:XML;
		private var _url:URLRequest;
		private var _path:String;
		private var _urlLoad:URLLoader;
		
		public function XmlLoader()
		{
			super();
		}
		
	    /**
	     * 设置外部XML文件路径
	     * @param xmlURL
	     */
	    public function set Path(xmlURL:String): void
	    {
			_path=xmlURL;
	    	_url=new URLRequest(xmlURL);
	    	_urlLoad=new URLLoader();
	    	_urlLoad.load(_url);
	    	_urlLoad.addEventListener(Event.COMPLETE,loadedHandle);
	    	_urlLoad.addEventListener(IOErrorEvent.IO_ERROR,ioErrorHandle);
	    }
	    
	    /**
	    * 只读访问xml对象
	    */
	    public function get xml():XML
	    {
	    	return _xml;
	    }
		/**
		 * 
		 * 
		 * */
		public function saveXml():void{
			trace("path:"+File.applicationDirectory.resolvePath(_path).nativePath);
			var dataFile:File = new File(File.applicationDirectory.resolvePath(_path).nativePath);
			var stream:FileStream = new FileStream();
			stream.openAsync(dataFile, FileMode.UPDATE);
			stream.writeUTFBytes(_xml);
			stream.close();
		}
		
	    /**
	    * _urlLoad.load 加载完成事件侦听器
	    */
	    private function loadedHandle(e:Event):void
	    {
	    	_xml=XML(_urlLoad.data);
			///trace("_xmal"+_xml);
	    	//Debugger.log("xmlLoader.loadedHandle:"+_xml);
	    	dispatchEvent(new Event(Event.COMPLETE));
	    }
	    private function ioErrorHandle(e:Event):void
	    {
	    	_xml=XML('<?xml version="1.0" encoding="UTF-8"?>');
	    	//Debugger.log("xmlLoader.ioErrorHandle:"+_xml);
	    	dispatchEvent(new Event(IOErrorEvent.IO_ERROR));
	    }
	    public function dispose():void
	    {
	    	_urlLoad.close();
	    	_urlLoad=null;
	    	_url=null;
	    	//_xml=null;
	    	//_path=null;
	    }

	}//end XmlLoad

}